package com.doubao.chat.service.impl;

import com.doubao.chat.dto.MessageProviderInfo;
import com.doubao.chat.entity.ChatMessage;
import com.doubao.chat.service.AIProviderService;
import com.doubao.common.exception.BusinessException;
import com.doubao.common.result.Result;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.service.SmartDeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * AI提供商服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
//@Primary  // <-- Remove this
public class AIProviderServiceImpl implements AIProviderService {

    private final SmartDeviceService deviceService;
    private final RestTemplate restTemplate;

    // AI提供商配置
    @Value("${chat.ai-providers.doubao.name:豆包AI}")
    private String doubaoProviderName;

    @Value("${chat.ai-providers.doubao.base-url:https://ark.cn-beijing.volces.com/api/v3/completions}")
    private String doubaoBaseUrl;

    @Value("${chat.ai-providers.doubao.default-endpoint-id:ep-20241227105403-wm97s}")
    private String doubaoDefaultEndpointId;

    @Value("${chat.ai-providers.doubao.default-api-key:f65fcf30-0c54-45ab-9fdc-e873c81f2fdf}")
    private String doubaoDefaultApiKey;

    @Value("${chat.ai-providers.deepseek.name:DeepSeek AI}")
    private String deepseekProviderName;

    @Value("${chat.ai-providers.deepseek.base-url:https://api.deepseek.com/v1/chat/completions}")
    private String deepseekBaseUrl;

    @Value("${chat.ai-providers.deepseek.default-api-key:sk-fdb461816f3b4ef2bc91be773e3a8773}")
    private String deepseekDefaultApiKey;

    @Value("${chat.ai-providers.dify.name:Dify AI}")
    private String difyProviderName;

    @Value("${chat.ai-providers.dify.base-url:https://api.dify.ai/v1/chat-messages}")
    private String difyBaseUrl;

    @Value("${chat.ai-providers.dify.default-api-key:app-PVbLtiFGVfS1ArsVcf2Y2AVG}")
    private String difyDefaultApiKey;

    @Value("${chat.ai-providers.coze.name:扣子AI}")
    private String cozeProviderName;

    @Value("${chat.ai-providers.coze.base-url:https://api.coze.cn/v3/chat}")
    private String cozeBaseUrl;

    @Value("${chat.ai-providers.coze.default-api-key:pat_dXmlpdKw5tnnHUeQTbzLpKYP40lMKYXTkNxqyJrvj65qgy4B9y8iS6fueCLurXdP}")
    private String cozeDefaultApiKey;

    @Value("${chat.ai-providers.coze.request-config.timeout:30000}")
    private int cozeTimeout;

    @Override
    public Result<MessageProviderInfo> getProviderInfo(Long deviceId) {
        try {
            // 获取智能体
            SmartDevice device = deviceService.getById(deviceId);
            if (device == null) {
                return Result.failed("智能体不存在");
            }

            Long providerId = device.getAiProviderId();
            String modelId = device.getAiModelId();

            // 构建提供商信息
            MessageProviderInfo providerInfo = new MessageProviderInfo();
            providerInfo.setProviderId(providerId);
            providerInfo.setModelId(modelId);

            // 根据提供商ID获取提供商信息
            if (providerId != null) {
                switch (providerId.intValue()) {
                    case 1: // 豆包AI
                        providerInfo.setProviderName(doubaoProviderName);
                        providerInfo.setProviderCode("doubao");
                        providerInfo.setModelName("豆包模型");
                        providerInfo.setModelCode("doubao-model");
                        providerInfo.setNeedsBotId(false);
                        break;
                    case 2: // DeepSeek AI
                        providerInfo.setProviderName(deepseekProviderName);
                        providerInfo.setProviderCode("deepseek");
                        providerInfo.setModelName("DeepSeek Chat");
                        providerInfo.setModelCode("deepseek-chat");
                        providerInfo.setNeedsBotId(false);
                        break;
                    case 3: // Dify AI
                        providerInfo.setProviderName(difyProviderName);
                        providerInfo.setProviderCode("dify");
                        providerInfo.setModelName("Dify Bot");
                        providerInfo.setModelCode("dify-bot");
                        providerInfo.setNeedsBotId(true);
                        break;
                    case 4: // 扣子AI
                        providerInfo.setProviderName(cozeProviderName);
                        providerInfo.setProviderCode("coze");
                        providerInfo.setModelName("Coze Bot");
                        providerInfo.setModelCode("coze-bot");
                        providerInfo.setNeedsBotId(true);
                        break;
                    default:
                        return Result.failed("不支持的AI提供商");
                }
            } else {
                return Result.failed("AI提供商ID为空");
            }

            return Result.success(providerInfo);
        } catch (Exception e) {
            log.error("获取AI提供商信息异常", e);
            return Result.failed("获取AI提供商信息异常: " + e.getMessage());
        }
    }

    @Override
    public Result<String> getSystemPrompt(Long deviceId) {
        try {
            // 获取智能体
            SmartDevice device = deviceService.getById(deviceId);
            if (device == null) {
                return Result.failed("智能体不存在");
            }

            // 获取提示词
            String prompt = device.getPrompt();
            if (!StringUtils.hasText(prompt)) {
                return Result.success(""); // 返回空字符串作为默认提示词
            }

            return Result.success(prompt);
        } catch (Exception e) {
            log.error("获取系统提示词异常", e);
            return Result.failed("获取系统提示词异常: " + e.getMessage());
        }
    }

    @Override
    public Result<String> sendMessageToProvider(Long deviceId, String systemPrompt, List<ChatMessage> contextMessages, String content) {
        try {
            // 获取智能体
            SmartDevice device = deviceService.getById(deviceId);
            if (device == null) {
                return Result.failed("智能体不存在");
            }

            // 获取提供商信息
            Long providerId = device.getAiProviderId();

            if (providerId == null) {
                return Result.failed("AI提供商ID为空");
            }

            // 根据不同提供商调用不同API
            String response;
            switch (providerId.intValue()) {
                case 1: // 豆包AI
                    response = callDoubaoAPI(device, systemPrompt, contextMessages, content);
                    break;
                case 2: // DeepSeek AI
                    response = callDeepSeekAPI(device, systemPrompt, contextMessages, content);
                    break;
                case 3: // Dify AI
                    response = callDifyAPI(device, systemPrompt, contextMessages, content);
                    break;
                case 4: // 扣子AI
                    response = callCozeAPI(device, systemPrompt, contextMessages, content);
                    break;
                default:
                    return Result.failed("不支持的AI提供商");
            }

            return Result.success(response);
        } catch (Exception e) {
            log.error("发送消息到AI提供商异常", e);
            return Result.failed("发送消息到AI提供商异常: " + e.getMessage());
        }
    }

    /**
     * 调用豆包API，支持bot_id格式
     */
    private String callDoubaoAPI(SmartDevice device, String systemPrompt, List<ChatMessage> contextMessages, String userMessage) {
        try {
            // 确定使用哪个API端点
            String apiUrl;

            // 判断是否使用bots格式的API - 检查aiModelId是否已经是bot-id格式
            boolean useBotApi = false;
            boolean isAlreadyBotId = false;

            if (device.getAiModelId() != null) {
                // 检查是否已经是bot-id格式
                isAlreadyBotId = device.getAiModelId().startsWith("bot-");

                if (isAlreadyBotId) {
                    useBotApi = true;
                    apiUrl = "https://ark.cn-beijing.volces.com/api/v3/bots/chat/completions";
                } else {
                    // 使用传统的completions端点
                    apiUrl = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
                }
            } else {
                // 默认使用传统端点
                apiUrl = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
            }

            log.info("调用豆包API - URL: {}, 使用Bot API: {}", apiUrl, useBotApi);

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 使用设备配置的API密钥，如果没有则使用默认密钥
            String apiKey = StringUtils.hasText(device.getApiKey()) ? device.getApiKey() : doubaoDefaultApiKey;
            headers.set("Authorization", "Bearer " + apiKey);

            // 构建消息列表
            List<Map<String, String>> messages = new ArrayList<>();

            // 添加系统提示词
            if (StringUtils.hasText(systemPrompt)) {
                Map<String, String> systemMessage = new HashMap<>();
                systemMessage.put("role", "system");
                systemMessage.put("content", systemPrompt);
                messages.add(systemMessage);
            }

            // 添加上下文消息
            for (ChatMessage message : contextMessages) {
                Map<String, String> contextMessage = new HashMap<>();
                contextMessage.put("role", message.getRole());
                contextMessage.put("content", message.getContent());
                messages.add(contextMessage);
            }

            // 添加用户消息
            Map<String, String> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);
            messages.add(userMsg);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("messages", messages);

            if (useBotApi) {
                // 使用bot API时，直接使用原始的bot-id，不要重复添加前缀
                String botId = device.getAiModelId();
                log.info("使用Bot ID: {}", botId);

                requestBody.put("model", botId); // 直接使用原始的bot-id

                // 设置流选项
                Map<String, Object> streamOptions = new HashMap<>();
                streamOptions.put("include_usage", true);
                requestBody.put("stream_options", streamOptions);
                requestBody.put("stream", false); // 默认不使用流式响应
            } else {
                // 使用传统API
                requestBody.put("model", "doubao-1.5-pro-32k-250115");

                // 使用设备配置的端点ID，如果没有则使用默认端点ID
                String endpointId = StringUtils.hasText(device.getApiEndpointId()) ? device.getApiEndpointId() : doubaoDefaultEndpointId;
                requestBody.put("endpoint_id", endpointId);
            }

            // 共同参数
            requestBody.put("temperature", 0.7);
            requestBody.put("top_p", 1.0);

            log.info("豆包API请求体: {}", requestBody);

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, Map.class);

            log.info("豆包API响应状态: {}", response.getStatusCode());

            // 解析响应
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (choices != null && !choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    if (choice != null && choice.containsKey("message")) {
                        Map<String, Object> message = (Map<String, Object>) choice.get("message");
                        if (message != null && message.containsKey("content")) {
                            return (String) message.get("content");
                        }
                    }
                }
            }

            log.error("无法解析豆包API响应: {}", responseBody);
            throw new BusinessException("无法解析豆包API响应");
        } catch (Exception e) {
            log.error("调用豆包API异常", e);
            throw new BusinessException("调用豆包API异常: " + e.getMessage());
        }
    }

    /**
     * 调用DeepSeek API (保留原实现)
     */
    private String callDeepSeekAPI(SmartDevice device, String systemPrompt, List<ChatMessage> contextMessages, String userMessage) {
        try {
            // 构建请求URL
            String apiUrl = deepseekBaseUrl;

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 使用设备配置的API密钥，如果没有则使用默认密钥
            String apiKey = StringUtils.hasText(device.getApiKey()) ? device.getApiKey() : deepseekDefaultApiKey;
            headers.set("Authorization", "Bearer " + apiKey);

            // 构建消息列表
            List<Map<String, String>> messages = new ArrayList<>();

            // 添加系统提示词
            if (StringUtils.hasText(systemPrompt)) {
                Map<String, String> systemMessage = new HashMap<>();
                systemMessage.put("role", "system");
                systemMessage.put("content", systemPrompt);
                messages.add(systemMessage);
            }

            // 添加上下文消息
            for (ChatMessage message : contextMessages) {
                Map<String, String> contextMessage = new HashMap<>();
                contextMessage.put("role", message.getRole());
                contextMessage.put("content", message.getContent());
                messages.add(contextMessage);
            }

            // 添加用户消息
            Map<String, String> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);
            messages.add(userMsg);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("messages", messages);
            requestBody.put("model", "deepseek-chat"); // 默认模型
            requestBody.put("temperature", 0.7);
            requestBody.put("top_p", 1.0);

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, Map.class);

            // 解析响应
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (choices != null && !choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    if (choice != null && choice.containsKey("message")) {
                        Map<String, Object> message = (Map<String, Object>) choice.get("message");
                        if (message != null && message.containsKey("content")) {
                            return (String) message.get("content");
                        }
                    }
                }
            }

            throw new BusinessException("无法解析DeepSeek API响应");
        } catch (Exception e) {
            log.error("调用DeepSeek API异常", e);
            throw new BusinessException("调用DeepSeek API异常: " + e.getMessage());
        }
    }

    /**
     * 调用Dify API (保留原实现)
     */
    private String callDifyAPI(SmartDevice device, String systemPrompt, List<ChatMessage> contextMessages, String userMessage) {
        try {
            // 构建请求URL
            String apiUrl = difyBaseUrl;

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 使用设备配置的API密钥，如果没有则使用默认密钥
            String apiKey = StringUtils.hasText(device.getApiKey()) ? device.getApiKey() : difyDefaultApiKey;
            headers.set("Authorization", "Bearer " + apiKey);

            // Dify需要使用bot_id，即AI模型ID
            String botId = String.valueOf(device.getAiModelId());

            // 构建会话ID（可选）
            String sessionId = "session_" + System.currentTimeMillis();

            // 构建上下文消息（Dify API格式）
            List<Map<String, Object>> conversationHistory = new ArrayList<>();
            for (ChatMessage message : contextMessages) {
                Map<String, Object> historyMessage = new HashMap<>();
                historyMessage.put("role", message.getRole());
                historyMessage.put("content", message.getContent());
                conversationHistory.add(historyMessage);
            }

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", new HashMap<>()); // Dify可能需要的参数
            requestBody.put("query", userMessage);
            requestBody.put("bot_id", botId);
            requestBody.put("conversation_id", sessionId);
            requestBody.put("user", "user_" + System.currentTimeMillis());

            if (!conversationHistory.isEmpty()) {
                requestBody.put("conversation_history", conversationHistory);
            }

            if (StringUtils.hasText(systemPrompt)) {
                Map<String, Object> response_mode = new HashMap<>();
                response_mode.put("type", "chat");
                response_mode.put("system_prompt", systemPrompt);
                requestBody.put("response_mode", response_mode);
            }

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, Map.class);

            // 解析响应
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("answer")) {
                return (String) responseBody.get("answer");
            }

            throw new BusinessException("无法解析Dify API响应");
        } catch (Exception e) {
            log.error("调用Dify API异常", e);
            throw new BusinessException("调用Dify API异常: " + e.getMessage());
        }
    }

    /**
     * 调用扣子API（使用HTTP方式）
     * 改进版本，处理用户ID和上下文问题
     */
    private String callCozeAPI(SmartDevice device, String systemPrompt, List<ChatMessage> contextMessages, String content) {
        try {
            // 验证设备参数
            if (device == null || device.getAiModelId() == null) {
                log.error("设备或AI模型ID为空 - device: {}, modelId: {}",
                        device, device != null ? device.getAiModelId() : null);
                throw new BusinessException("设备或AI模型ID为空");
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 使用设备配置的API密钥，如果没有则使用默认密钥
            String apiKey = StringUtils.hasText(device.getApiKey()) ? device.getApiKey() : cozeDefaultApiKey;
            if (!StringUtils.hasText(apiKey)) {
                throw new BusinessException("扣子API密钥未配置");
            }
            headers.set("Authorization", "Bearer " + apiKey);

            // 使用设备的ai_model_id作为bot_id
            String botId = String.valueOf(device.getAiModelId());

            // 使用固定用户ID，格式为"user_" + 设备ID + "_" + 用户ID
            String userId = "user_" + device.getId() + "_" + device.getUserId();

            // 构建消息列表
            List<Map<String, Object>> additionalMessages = new ArrayList<>();

            // 添加历史消息
            if (contextMessages != null) {
                for (ChatMessage msg : contextMessages) {
                    Map<String, Object> historyMsg = new HashMap<>();
                    historyMsg.put("role", msg.getRole());
                    historyMsg.put("content", msg.getContent());
                    historyMsg.put("content_type", "text");
                    additionalMessages.add(historyMsg);
                }
            }

            // 添加当前用户消息
            Map<String, Object> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", content);
            userMsg.put("content_type", "text");
            additionalMessages.add(userMsg);

            // 使用v3的chat接口发起对话
            String apiUrl = cozeBaseUrl;

            // 构建符合v3规范的请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("bot_id", botId);
            requestBody.put("user_id", userId);
            requestBody.put("stream", false);
            requestBody.put("auto_save_history", true);
            requestBody.put("additional_messages", additionalMessages);

            if (StringUtils.hasText(systemPrompt)) {
                // 如果有系统提示词，添加它
                Map<String, Object> system = new HashMap<>();
                system.put("prompt", systemPrompt);
                requestBody.put("system", system);
            }

            // 打印完整的请求信息用于调试
            log.info("调用扣子API - 请求URL: {}", apiUrl);
            log.info("调用扣子API - Bot ID: {}", botId);
            log.info("调用扣子API - 用户ID: {}", userId);
            log.info("扣子API请求体: {}", requestBody);

            // 创建带有更长超时时间的RestTemplate
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setConnectTimeout(cozeTimeout);
            factory.setReadTimeout(cozeTimeout);
            RestTemplate customRestTemplate = new RestTemplate(factory);

            try {
                // 发送请求 - 使用Map接收响应
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
                ResponseEntity<Map> response = customRestTemplate.exchange(
                        apiUrl, HttpMethod.POST, entity, Map.class);

                // 打印响应状态和头信息
                log.info("扣子API响应状态码: {}", response.getStatusCode().value());

                // 更详细的响应解析和错误处理
                if (response.getStatusCode().is2xxSuccessful()) {
                    Map<String, Object> responseBody = response.getBody();
                    if (responseBody == null) {
                        log.error("扣子API返回空响应体");
                        throw new BusinessException("扣子API返回空响应体");
                    }

                    // 打印响应体的键集合，避免打印整个响应体
                    log.info("扣子API响应体键集: {}", responseBody.keySet());

                    // 处理扣子API的标准响应格式：{code, msg, data}
                    if (responseBody.containsKey("code")) {
                        Object codeObj = responseBody.get("code");
                        int code = codeObj instanceof Number ? ((Number) codeObj).intValue() : -1;

                        if (code == 0 || code == 200) { // 成功状态码
                            if (responseBody.containsKey("data")) {
                                Map<String, Object> dataMap = (Map<String, Object>) responseBody.get("data");
                                log.info("扣子API data字段键集: {}", dataMap.keySet());

                                // 获取chatId和conversationId，用于后续请求
                                String chatId = null;
                                String conversationId = null;

                                if (dataMap.containsKey("id")) {
                                    chatId = String.valueOf(dataMap.get("id"));
                                    log.info("扣子API chatId: {}", chatId);
                                }

                                if (dataMap.containsKey("conversation_id")) {
                                    conversationId = String.valueOf(dataMap.get("conversation_id"));
                                    log.info("扣子API conversationId: {}", conversationId);
                                }

                                if (chatId != null && conversationId != null) {
                                    // 等待并检查对话状态，直到完成或超时
                                    if (waitForChatCompletion(customRestTemplate, apiKey, chatId, conversationId)) {
                                        // 获取对话消息
                                        return getChatMessages(customRestTemplate, apiKey, chatId, conversationId);
                                    } else {
                                        return "智能体回复处理超时";
                                    }
                                } else {
                                    log.error("扣子API响应中缺少必要的ID信息");
                                    throw new BusinessException("扣子API响应中缺少必要的ID信息");
                                }
                            }
                        } else {
                            // API返回了错误码
                            String msg = responseBody.containsKey("msg") ? (String) responseBody.get("msg") : "未知错误";
                            log.error("扣子API返回错误 - 代码: {}, 消息: {}", code, msg);
                            throw new BusinessException("扣子API返回错误: " + msg);
                        }
                    }

                    // 如果找不到有效的响应内容，返回错误信息
                    log.error("扣子API响应解析失败，无法找到有效内容字段，响应键集: {}", responseBody.keySet());
                    throw new BusinessException("扣子API响应解析失败，无法找到有效内容");
                } else {
                    log.error("扣子API请求失败 - 状态码: {}", response.getStatusCode().value());
                    throw new BusinessException("扣子API请求失败: " + response.getStatusCode());
                }
            } catch (RestClientException e) {
                log.error("调用扣子API网络异常 - URL: {}, 错误: {}", apiUrl, e.getMessage());
                throw new BusinessException("调用扣子API网络异常: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("调用扣子API处理异常", e);
            throw new BusinessException("调用扣子API处理异常: " + e.getMessage());
        }
    }

    /**
     * 等待对话完成
     * 优化版本：使用动态等待时间，减少轮询次数
     */
    private boolean waitForChatCompletion(RestTemplate customRestTemplate, String apiKey, String chatId, String conversationId) {
        // 最多等待30秒，初始轮询间隔500ms，逐渐增加到2秒
        int maxAttempts = 30;
        long baseWaitTimeMs = 500;
        long maxWaitTimeMs = 2000;

        for (int attempt = 0; attempt < maxAttempts; attempt++) {
            try {
                // 构建请求URL
                String apiUrl = "https://api.coze.cn/v3/chat/retrieve";
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                        .queryParam("chat_id", chatId)
                        .queryParam("conversation_id", conversationId);

                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", "Bearer " + apiKey);
                headers.setContentType(MediaType.APPLICATION_JSON);

                HttpEntity<Void> entity = new HttpEntity<>(headers);
                ResponseEntity<Map> response = customRestTemplate.exchange(
                        builder.toUriString(), HttpMethod.GET, entity, Map.class);

                if (response.getStatusCode().is2xxSuccessful()) {
                    Map<String, Object> responseBody = response.getBody();
                    if (responseBody != null && responseBody.containsKey("code") &&
                            ((Number)responseBody.get("code")).intValue() == 0) {

                        if (responseBody.containsKey("data")) {
                            Map<String, Object> dataMap = (Map<String, Object>) responseBody.get("data");
                            if (dataMap.containsKey("status")) {
                                String status = (String) dataMap.get("status");
                                log.info("对话状态: {}", status);

                                if ("completed".equals(status)) {
                                    return true;
                                } else if ("failed".equals(status)) {
                                    log.error("对话处理失败");
                                    return false;
                                }
                            }
                        }
                    }
                }

                // 计算动态等待时间，随着尝试次数增加而增加
                long waitTime = Math.min(baseWaitTimeMs + (attempt * 200), maxWaitTimeMs);
                Thread.sleep(waitTime);
            } catch (Exception e) {
                log.error("检查对话状态异常", e);
                // 继续尝试
            }
        }

        // 超时
        log.error("等待对话完成超时");
        return false;
    }

    /**
     * 获取对话消息内容
     */
    private String getChatMessages(RestTemplate customRestTemplate, String apiKey, String chatId, String conversationId) {
        try {
            // 构建请求URL
            String apiUrl = "https://api.coze.cn/v3/chat/message/list";
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                    .queryParam("chat_id", chatId)
                    .queryParam("conversation_id", conversationId);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiKey);
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Void> entity = new HttpEntity<>(headers);
            ResponseEntity<Map> response = customRestTemplate.exchange(
                    builder.toUriString(), HttpMethod.GET, entity, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> responseBody = response.getBody();
                if (responseBody != null && responseBody.containsKey("code") &&
                        ((Number)responseBody.get("code")).intValue() == 0) {

                    if (responseBody.containsKey("data")) {
                        List<Map<String, Object>> dataList = (List<Map<String, Object>>) responseBody.get("data");
                        if (dataList != null && !dataList.isEmpty()) {
                            // 遍历所有消息，查找type为answer的消息
                            for (Map<String, Object> message : dataList) {
                                if (message.containsKey("type") && "answer".equals(message.get("type")) &&
                                        message.containsKey("content")) {
                                    return (String) message.get("content");
                                }
                            }
                        }
                    }
                }
            }

            // 尝试获取对话详情，可能包含回复内容
            return getConversationDetails(customRestTemplate, apiKey, chatId, conversationId);
        } catch (Exception e) {
            log.error("获取对话消息异常", e);
            return "获取回复内容时出错: " + e.getMessage();
        }
    }

    /**
     * 获取对话详情，作为备用方案
     */
    private String getConversationDetails(RestTemplate customRestTemplate, String apiKey, String chatId, String conversationId) {
        try {
            // 构建请求URL，使用v3接口
            String apiUrl = "https://api.coze.cn/v3/chat/retrieve";
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("chat_id", chatId);
            requestBody.put("conversation_id", conversationId);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiKey);
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = customRestTemplate.exchange(
                    apiUrl, HttpMethod.POST, entity, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> responseBody = response.getBody();
                if (responseBody != null && responseBody.containsKey("data")) {
                    Map<String, Object> dataMap = (Map<String, Object>) responseBody.get("data");
                    // 可能包含回复内容的字段，根据实际API响应调整
                    if (dataMap.containsKey("reply_text")) {
                        return (String) dataMap.get("reply_text");
                    } else if (dataMap.containsKey("reply")) {
                        return (String) dataMap.get("reply");
                    }
                }
            }

            return "无法获取智能体回复内容";
        } catch (Exception e) {
            log.error("获取对话详情异常", e);
            return "获取对话详情时出错: " + e.getMessage();
        }
    }
}